package com.joker.orange.service;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.joker.common.constant.CacheConstants;
import com.joker.common.constant.Constants;
import com.joker.common.core.domain.entity.SysUser;
import com.joker.common.core.domain.event.LogininforEvent;
import com.joker.common.core.domain.model.LoginUser;
import com.joker.common.enums.DeviceType;
import com.joker.common.enums.LoginType;
import com.joker.common.enums.UserStatus;
import com.joker.common.enums.UserType;
import com.joker.common.exception.user.UserException;
import com.joker.common.helper.LoginHelper;
import com.joker.common.utils.DateUtils;
import com.joker.common.utils.MessageUtils;
import com.joker.common.utils.ServletUtils;
import com.joker.common.utils.redis.RedisUtils;
import com.joker.common.utils.spring.SpringUtils;
import com.joker.orange.domain.UserInfo;
import com.joker.orange.mapper.UserInfoMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

@RequiredArgsConstructor
@Slf4j
@Service
public class LoginService {

    @Value("${user.password.maxRetryCount}")
    private Integer maxRetryCount;

    @Value("${user.password.lockTime}")
    private Integer lockTime;

    private final UserInfoMapper userInfoMapper;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password, String type) {

        UserInfo user = loadUserByUsername(username);
        if ("0".equals(type)) {
            checkLogin(LoginType.PASSWORD, username, () -> !BCrypt.checkpw(password, user.getPassword()));
        } else if ("1".equals(type)) {
            checkLogin(LoginType.PASSWORD, username, () -> !user.getPassword().equals(password));
        }
        // 此处可根据登录用户的数据不同 自行创建 loginUser
        LoginUser loginUser = buildAppLoginUser(user);
        // 生成token
        LoginHelper.loginByDevice(loginUser, DeviceType.APP);

        recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
        recordLoginInfo(user.getId(), username);
        return StpUtil.getTokenValue();
    }

    private UserInfo loadUserByUsername(String username) {
        UserInfo user = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
            .select(UserInfo::getAccount, UserInfo::getStatus)
            .eq(UserInfo::getAccount, username));
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UserException("user.not.exists", username);
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new UserException("user.blocked", username);
        }
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
            .eq(UserInfo::getAccount, username));
    }

    /**
     * 构建登录用户
     */
    private LoginUser buildAppLoginUser(UserInfo user) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getId());
        loginUser.setUsername(user.getAccount());
        loginUser.setUserType("app_user");
        return loginUser;
    }

    /**
     * 登录校验
     */
    private void checkLogin(LoginType loginType, String username, Supplier<Boolean> supplier) {
        String errorKey = CacheConstants.PWD_ERR_CNT_KEY + username;
        String loginFail = Constants.LOGIN_FAIL;

        // 获取用户登录错误次数(可自定义限制策略 例如: key + username + ip)
        Integer errorNumber = RedisUtils.getCacheObject(errorKey);
        // 锁定时间内登录 则踢出
        if (ObjectUtil.isNotNull(errorNumber) && errorNumber.equals(maxRetryCount)) {
            recordLogininfor(username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime));
            throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
        }

        if (supplier.get()) {
            // 是否第一次
            errorNumber = ObjectUtil.isNull(errorNumber) ? 1 : errorNumber + 1;
            // 达到规定错误次数 则锁定登录
            if (errorNumber.equals(maxRetryCount)) {
                RedisUtils.setCacheObject(errorKey, errorNumber, Duration.ofMinutes(lockTime));
                recordLogininfor(username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime));
                throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
            } else {
                // 未达到规定错误次数 则递增
                RedisUtils.setCacheObject(errorKey, errorNumber);
                recordLogininfor(username, loginFail, MessageUtils.message(loginType.getRetryLimitCount(), errorNumber));
                throw new UserException(loginType.getRetryLimitCount(), errorNumber);
            }
        }

        // 登录成功 清空错误次数
        RedisUtils.deleteObject(errorKey);
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId, String username) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userId", userId);
            map.put("loginIp", ServletUtils.getClientIP());
            map.put("loginDate", DateUtils.getNowDate());
            map.put("updateBy", username);
            userInfoMapper.updateUserInfoByUserId(map);

    }

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息内容
     */
    private void recordLogininfor(String username, String status, String message) {
        LogininforEvent logininforEvent = new LogininforEvent();
        logininforEvent.setUsername(username);
        logininforEvent.setStatus(status);
        logininforEvent.setMessage(message);
        logininforEvent.setRequest(ServletUtils.getRequest());
        SpringUtils.context().publishEvent(logininforEvent);
    }

}
